package simportal.service;

import java.lang.reflect.Method;

import simportal.utils.BeanUtil;

import com.cfuture08.eweb4j.orm.config.ORMConfigBeanUtil;
import com.cfuture08.eweb4j.orm.dao.base.BaseDAOImpl;
import com.cfuture08.eweb4j.orm.dao.cascade.CascadeDAO;
import com.cfuture08.eweb4j.orm.dao.factory.DAOFactory;
import com.cfuture08.util.ReflectUtil;

/**
 * 通用服务类
 * 
 * @author weiwei
 * 
 */
public class BaseService<T> extends BaseDAOImpl<T> {
	CascadeDAO cascadeDAO = DAOFactory.getCascadeDAO();

	public BaseService(Class<T> cls) {
		super(cls);
	}

	/**
	 * 批量删除
	 * 
	 * @param ids
	 * @return
	 */
	public String batchRemove(Integer[] ids) {
		if (ids == null || ids.length == 0) {
			return "请选择要删除的信息";
		}

		StringBuilder sb = new StringBuilder();

		for (Integer id : ids) {
			if (sb.length() > 0) {
				sb.append(",");
			}
			sb.append(id);
		}

		String error = this.delete(ids);
		if (error != null) {
			sb.append(error);
			return sb.toString();
		}

		return null;
	}

	/**
	 * 创建
	 * 
	 * @param navMenu
	 * @return
	 */
	public String create(T t, String pk, String desc) {
		if (t == null) {
			return "无法添加";
		}
		if (pk != null && desc != null) {
			// 如果违反主键约束
			T _t = DAOFactory.getSelectDAO().selectOne(t, pk);
			if (_t != null) {
				return "输入的[" + desc + "]和系统现有的重复";
			}
		}

		return this.create(t);
	}

	/**
	 * 修改
	 * 
	 * @param navMenu
	 * @return
	 */
	public String update(T t, String pk, String desc) {
		try {
			ReflectUtil ru = new ReflectUtil(t);
			Method m = ru.getGetter(ORMConfigBeanUtil.getIdField(t.getClass()));
			Integer id = (Integer) (m == null ? 0 : m.invoke(t));
			if (t == null || id == null || id == 0) {
				return "无法修改";
			}
			if (pk != null && desc != null) {
				// 如果违反主键约束
				T _t = DAOFactory.getSelectDAO().selectOne(t, pk);
				if (_t != null) {
					try {
						Object _idValObj = BeanUtil.getIdVal(_t);
						Object idValObj = BeanUtil.getIdVal(t);

						if (_idValObj != null && idValObj != null)
							if (!_idValObj.equals(idValObj))
								return "输入的[" + desc + "]和系统现有的重复";

					} catch (Exception e) {
						return "idGetter invoke exception.";
					}
				}
			}

			return this.update(t);

		} catch (Exception e) {
			return e.getMessage();
		}
	}

}
